package org.xtense.engine;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.xtense.log.iLog;
import org.xtense.model.CAttribute;
import org.xtense.model.CDocument;
import org.xtense.model.CElement;
import org.xtense.model.CSubSet;
import org.xtense.model.CText;
import org.xtense.model.PathEntry;

public class XtenseFactory {

	private XtenseFactory() {

	}

	private static XtenseFactory instance;

	public static XtenseFactory instance() {
		if (instance == null) {
			instance = new XtenseFactory();
		}
		return instance;
	}

	/**
	 * Create a CSubSet instance.
	 * 
	 * @return
	 */
	public CSubSet createResultSetForQuery(int documentId) {
		return new CSubSet(documentId);
	}

	/**
	 * Using the data in the result set to fill the CSubSet.
	 * 
	 * @param cSet
	 * @param resultSet
	 * @param type
	 */
	public void generateResulte(CSubSet cSet, ResultSet resultSet, int type) {
		try {
			// TODO fill path in csubset
			switch (type) {
			case IConstants.ATTRIBUTE:
				iLog.info("Fill the attributes to the result...");
				while (resultSet.next()) {
					cSet.addAttribute(new CAttribute(resultSet
							.getInt(IConstants.Element_Pre), resultSet
							.getString(IConstants.Attribute_Name), resultSet
							.getString(IConstants.Attribute_Value)));
				}
				break;
			case IConstants.ELEMENT:
				iLog.info("Fill the elements to the result...");
				while (resultSet.next()) {
					cSet.addElement(new CElement(resultSet
							.getInt(IConstants.Element_Pre), resultSet
							.getString(IConstants.Element_Tag), resultSet
							.getInt(IConstants.Parent_Pre)));
				}
				break;
			case IConstants.TEXT:
				iLog.info("Fill the text to the result...");
				while (resultSet.next()) {
					cSet.addText(new CText(resultSet
							.getInt(IConstants.Element_Pre), resultSet
							.getString(IConstants.Text_Content)));
				}
				break;
			case IConstants.DOCUMENT:
				iLog.info("Fill the document to the result...");
				resultSet.next();
				if (cSet instanceof CDocument) {
					((CDocument) cSet).setDocumentName(resultSet
							.getString(IConstants.Document_Name));
				} else {
					cSet = new CDocument(cSet, resultSet
							.getString(IConstants.Document_Name));
				}
				break;
			case IConstants.PATH:
				iLog.info("Fill the path to the result...");
				while (resultSet.next()) {
					cSet.addPath(new PathEntry(resultSet
							.getInt(IConstants.Element_Pre), resultSet
							.getString(IConstants.Path_Content)));
				}
				break;
			}
		} catch (SQLException e) {
			iLog.error(e);
		}
	}
}
